/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dorian.atomicuml.models;

import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author cedric.creusot
 */
public class LoginValidator implements Validator {

    private MessageSource messageSource;
    
    public LoginValidator(MessageSource messageSource)
    {
        super();
        this.messageSource = messageSource;
    }
    
    @Override
    public boolean supports(Class<?> type) {
        return UserInfoData.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        try
        {
            final String ERROR1 = messageSource.getMessage("login.errors.login", null, Locale.FRENCH);
            final String ERROR2 = messageSource.getMessage("login.errors.emtpy", null, Locale.FRENCH);
            
            UserInfoData uid = (UserInfoData)o;
            
            ValidationUtils.rejectIfEmptyOrWhitespace(errors,
                                                      "password",
                                                      "errors.required",
                                                      new Object[] {"password"},
                                                      ERROR2);

            ValidationUtils.rejectIfEmptyOrWhitespace(errors,
                                                      "mail",
                                                      "errors.required",
                                                      new Object[] {"mail"},
                                                      ERROR2);
            if (!uid.isMailValid()){
                 errors.rejectValue("mail",
                                   "errors.required",
                                   new Object[] {"mail"},
                                   ERROR1);
            }

        }
        catch (Exception e)
        {
            System.out.println("Validator error :" + e);
        }
    }
    
}
